
import BaseSDK from "./BaseSdk"
import SDKEvent from "./SDKEvent";

export default class TTSDK extends BaseSDK {

    private static _instance: TTSDK = null;
    public static get Instance(): TTSDK {
        this._instance = this._instance || new TTSDK();
        return this._instance;
    }

    public isLogin: boolean = false;
    private _recorderShareFunc = null;
    private _musicPauseFunc = null;
    private _musicPauseThis = null;
    private _musicResumeFunc = null;
    private _musicResumeThis = null;
    private _clipboardData = "";

    private _playScreenTime = 0;
    private _screenSpaceTime = 0;
    private _interstitiaId = "";
    private _moreGameBtn = null;

    // @ts-ignore
    private _recorder = null;//录屏器
    private _videoPath: string = "";//录屏得到的视频地址
    private _recorderStatus = 0;
    private _recorderEndTime = 0;
    private _recorderTime = 0;
    private _bannerId = "fi84ao2ae868g6is9q";
    private _videoId = "216bf1cdae4d517idi";
    private _screenId = "ni4p6nf6hpof7i796j";
    private _shareUrl = "";
    private _shareId = "2r2m932qedg4hd3i3f";
    private _shareTitle = "三连消除";
    private _shareDesc = "动用你聪明的脑袋来试试看";
    private _videoTopics = ["猪猪消除", "三连消除", "消除小游戏"];
    private _videoLoaded = false;
    private _videoOptions = null;
    private _videoAd = null;
    private _interstitiaAd = null;
    private _bannerLoaded = false;
    private lastAdTime = 0;//最后一次插屏播放时间
    private banner = null;
    private bannerCount: number = 0;//banner显示次数
    private lastshockTime = 0;//最后震动时间
    private screenShow: boolean = false;//插屏是否显示
    private shareValue = 1;
    private _shakeState: boolean; //震动的状态
    private isSidebarShowed: boolean = false;

    init() {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        this._shakeState = false;
        this.showShareMenu(true);
        globalThis.tt.onShareAppMessage(this.shareAppMessageCallback.bind(this));
        let that = this;
        this.lastAdTime = new Date().getTime();
        //初始化录屏
        // this._recorder = globalThis.tt.getGameRecorderManager();
        // this._recorder.onStop(res => {
        //     // 对录制完成的视频进行剪辑(最多生成30秒的视频)
        //     that._recorder.clipVideo({
        //         path: res.videoPath,
        //         timeRange: [25, 0],
        //         success(clipRes) {
        //             // 由开始10秒 +最后20秒 拼接合成的视频
        //             that._videoPath = clipRes.videoPath;
        //             console.log("剪辑完成", clipRes.videoPath);
        //         },
        //         fail(e) {
        //             console.error(e);
        //         },
        //     });
        //     if (res.videoPath) {
        //         that._videoPath = res.videoPath;
        //     } else {
        //         that._videoPath = "";
        //     }
        //     that._recorderStatus = 0;
        //     that._recorderEndTime = new Date().getTime();
        //     console.log("录屏结束", that._recorderEndTime);
        // });
        // this._recorder.onStart(res => {
        //     that._recorderTime = new Date().getTime();
        //     that._videoPath = "";
        //     that._recorderStatus = 1;
        //     console.log("录屏开始", that._recorderTime);
        // });

        globalThis.tt.onShow((res) => {
            console.log("********游戏回到前台************");
            console.log("启动参数：", res.query);
            console.log("来源信息：", res.refererInfo);
            console.log("场景值：", res.scene);
            //抖音首页侧边栏  "homepage"    "sidebar_card"
            console.log("启动场景字段：", res.launch_from, ", ", res.location);
            if (res.launch_from === "homepage" && res.location === "sidebar_card") {
                this.isSidebarShowed = true;
            }
        });
        this.checkNewVersion();
        globalThis.tt.setKeepScreenOn({ keepScreenOn: true });
        this.loadBanner(false);
    }

    //检查版本更新
    private checkNewVersion() {
        let updateManager = globalThis.tt.getUpdateManager();
        if (!updateManager) return;
        // 获取全局唯一的版本更新管理器，用于管理小程序更新
        updateManager.onCheckForUpdate(function (res) {
            // 监听向微信后台请求检查更新结果事件
            console.log("是否有新版本：" + res.hasUpdate);
            if (res.hasUpdate) {
                //如果有新版本
                // 小程序有新版本，会主动触发下载操作
                updateManager.onUpdateReady(function () {
                    //当新版本下载完成，会进行回调
                    globalThis.tt.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，单击确定重启小程序',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                                updateManager.applyUpdate();
                            }
                        }
                    })
                })
                // 小程序有新版本，会主动触发下载操作（无需开发者触发）
                updateManager.onUpdateFailed(function () {
                    //当新版本下载失败，会进行回调
                    globalThis.tt.showModal({
                        title: '提示',
                        content: '检查到有新版本，但下载失败，请稍后尝试',
                        showCancel: false,
                    })
                })
            }
        });

    }

    //显示转发按钮
    private showShareMenu(bool: boolean) {
        if (bool) {
            globalThis.tt.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            })
        } else {
            globalThis.tt.showShareMenu({ withShareTicket: false });//设置分享按钮，
        }
    }

    private shareAppMessageCallback() {
        let data = this.getShareConfig();
        return {
            title: this._shareTitle,
            imageUrl: data.url,
            templateId: data.id,
            query: "",
            desc: data.desc,
            success() {
                console.log("分享成功");
                this._shareOptions && this._shareOptions.success && this._shareOptions.success();
            },
            fail(e) {
                console.log("分享失败");
                this._shareOptions && this._shareOptions.fail && this._shareOptions.fail();
            },
        }
    }

    private getShareConfig() {
        let data = { url: null, id: "", desc: "" };
        switch (this.shareValue) {
            case 1:
                data.url = this._shareUrl;
                data.id = this._shareId;
                break;
            case 2:
                //本地分享,需要配置本地图片
                // let ran = Tools.getRandomInt(0, GameConfig.Instance.shares.length - 1);
                // data.url = GameConfig.Instance.shares[ran].nativeUrl
                break;
            case 3:
                let canvas = globalThis.tt.createCanvas();
                data.url = canvas.toTempFilePathSync({
                    destWidth: 500,
                    destHeight: 400
                })
                break;
            default:
                data = { url: null, id: "", desc: "" };
        }
        data.desc = this._shareDesc;
        return data;
    }

    private loadBanner(show: boolean = false) {
        let that = this;
        //创建banner
        const { windowWidth, windowHeight } = globalThis.tt.getSystemInfoSync();
        var targetBannerAdWidth = 200;
        if (that.banner != null) {
            that.banner.hide();
            if (that.banner.destroy) {
                that.banner.destroy();
            }
        }
        // 创建一个居于屏幕底部正中的广告
        this.banner = globalThis.tt.createBannerAd({
            adUnitId: that._bannerId,
            style: {
                width: targetBannerAdWidth,
                height: 100,
                left: (windowWidth - targetBannerAdWidth) / 2,
                top: windowHeight - (targetBannerAdWidth / 16) * 9, // 根据系统约定尺寸计算出广告高度
            },
        });
        this.banner.onLoad(function () {
            if (show) {
                that.banner.show();
            }
        });
        this.banner.onError(function (res) {
            if (globalThis.tt.createMoreGamesBanner) {
                that.banner = globalThis.tt.createMoreGamesBanner({
                    style: {
                        left: 0,
                        top: windowHeight - 100,
                        width: 150,
                        horizontalAlign: "center",
                    },
                    appLaunchOptions: []
                });
                that.banner.onTap(() => {
                    console.log("点击跳转游戏盒子");
                });
                that.banner.onResize(res => {

                });
            }
        });
        this.banner.onResize((size) => {
            that.banner.style.top = windowHeight - size.height;
            that.banner.style.left = (windowWidth - size.width) / 2;
        });
    }
    showBanner() {
        try {
            if (this.banner) {
                this.bannerCount++;
                if (this.bannerCount >= 10) {
                    this.loadBanner(true);
                    this.bannerCount = 0;
                } else {
                    this.banner.show();
                }

            } else {
                console.log('showBanner:未获取到banner对象');
            }
        } catch (error) {
            console.log(error);
        }
    }
    hideBanner() {
        try {
            if (this.banner) {
                this.banner.hide();
            } else {
                console.log('hideBanner:未获取到banner对象');
            }
        } catch (error) {
            console.log(error);
        }
    }

    setKeepScreenOn(options) {
        globalThis.tt.setKeepScreenOn(options);
    }

    //获取用户授权状态
    getTTSetting(options: { success: Function, fail: Function }) {
        globalThis.tt.getSetting({
            withSubscriptions: true,
            success: (res) => {
                // authSetting: {scope.userInfo: false, scope.screenRecord: true}
                let isGetUseInfo: boolean = res.authSetting["scope.userInfo"];
                if (isGetUseInfo) {
                    options.success && options.success(res);
                } else {
                    options.fail && options.fail(res);
                }
            },
            fail: (res) => {
                options.fail && options.fail(res);
            }
        })
    }

    //打开用户授权界面
    openTTSetting(options: { success?: Function, fail?: Function }) {
        globalThis.tt.openSetting({
            withSubscriptions: true,
            success: () => {

            },
            fail: () => {

            }
        })
    }

    /**
     * 小程序仅在 API/组件 首次 调用/使用时弹窗询问用户。若用户允许则正常调用，否则本次调用失败。
     * 且在用户手动授权之前，开发者再次调用需要授权 API 时，会直接进入接口的 fail 回调
     * @param options
     */
    login(options: { force: boolean, success: Function, fail: Function }) {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        let that = this;
        globalThis.tt.login({
            force: options.force,
            success(res) {
                console.log(`login 调用成功 ${res.code} ${res.anonymousCode}`);
                let userCode: string = res.code;
                let visitorCode: string = res.anonymousCode;
                let isLogin: boolean = res.isLogin;
                if (isLogin) {
                    globalThis.tt.getUserInfo({
                        success: (res) => {
                            console.log(`getUserInfo 调用成功`, res);
                            that.isLogin = true;
                            PlayerDataManager.setPlayerInfo(res.userInfo.nickName, res.userInfo.avatarUrl);
                            options.success && options.success(res);
                            // let userJson = JSON.stringify(res.userInfo);
                            // let data = {
                            //     code: userCode,
                            //     json: userJson,
                            //     visitor: false
                            // };
                            // that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
                            //     let result = res.data;
                            //     if (result.user.status == 0) {
                            //         console.log("登录完成，准备回调");
                            //         options.success(result);
                            //     } else {
                            //         console.log("用户状态异常");
                            //         options.fail("你因违规操作,帐号已被系统冻结");
                            //     }
                            // }, (res) => {
                            //     console.log(`request调用失败`, res);
                            //     options.fail("网络繁忙,请稍后再试");
                            // })
                        },
                        fail: (res) => {
                            console.log(`getUserInfo 调用失败`, res);
                            that.isLogin = false;
                            globalThis.tt.showModal({
                                title: '授权提示',
                                content: "请授权使用昵称和头像",
                                showCancel: true,
                                success: (res) => {
                                    if (res.confirm) {
                                        that.openTTSetting({});
                                    }
                                }
                            })

                            //游客登录
                            // let data = {
                            //     code: visitorCode,
                            //     json: "{}",
                            //     visitor: true
                            // };
                            // that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
                            //     let result = res.data;
                            //     if (result.user.status == 0) {
                            //         console.log("登录完成，准备回调");
                            //         options.success(result);
                            //     } else {
                            //         console.log("用户状态异常");
                            //         options.fail("你因违规操作,帐号已被系统冻结");
                            //     }
                            // }, (res) => {
                            //     console.log(`request调用失败`, res);
                            //     options.fail("网络繁忙,请稍后再试");
                            // });
                        }
                    })
                } else {
                    //游客登录
                    that.isLogin = false;
                    // let data = {
                    //     code: visitorCode,
                    //     json: "{}",
                    //     visitor: true
                    // };
                    // that.sendHttpRequest(Common.ttLoginUrl, data, (res) => {
                    //     let result = res.data;
                    //     if (result.user.status == 0) {
                    //         console.log("登录完成，准备回调");
                    //         options.success(result);
                    //     } else {
                    //         console.log("用户状态异常");
                    //         options.fail("你因违规操作,帐号已被系统冻结");
                    //     }
                    // }, (res) => {
                    //     console.log(`request调用失败`, res);
                    //     options.fail("网络繁忙,请稍后再试");
                    // });
                }
            },
            fail(res) {
                console.log(`login调用失败`, res);
                that.isLogin = false;
                options.fail && options.fail("登录失败,请稍后再试");
            },
        });
    }

    createMoreGamesButton(options) {
        if (this._moreGameBtn) {
            return;
        }
        console.log("创建更多游戏");
        this._moreGameBtn = globalThis.tt.createMoreGamesButton({
            type: "image",
            image: "images/moregame.png",
            style: {
                left: options.left,
                top: options.top,
                width: options.width,
                height: options.height,
                lineHeight: 49,
                backgroundColor: "#00000000",
                textColor: "#ffffff",
                textAlign: "center",
                fontSize: 16,
                borderRadius: 4,
                borderWidth: 1,
                borderColor: "#00000000"
            },
            appLaunchOptions: [],
            onNavigateToMiniGame(res) {
                console.log("跳转其他小游戏", res);
            }
        });
        this._moreGameBtn.onTap(() => {
            console.log("点击更多游戏");
        });
    }

    getOpenDataContext() {
        return globalThis.tt.getOpenDataContext();
    }

    postMessage(msg) {
        console.log("推送开放数据", msg);
        const openCtx = globalThis.tt.getOpenDataContext();
        openCtx.postMessage(msg);
    }

    startRecorder() {
        if (!this._recorder || this._isRecorder) {
            return;
        }
        this._recorderTime = new Date().getTime();
        this._isRecorder = true;
        this._recorder.start({
            duration: 300
        });

        cc.systemEvent.emit(SDKEvent.CHANGE_RECORDER_STATE);
    }

    stopRecorder(shareFunc?: Function) {
        if (!this._recorder || !this._isRecorder) {
            return;
        }
        this._recorderEndTime = new Date().getTime();
        this._recorderShareFunc = shareFunc;
        this._recorder.stop();
        this._isRecorder = false;
        cc.systemEvent.emit(SDKEvent.CHANGE_RECORDER_STATE);
    }

    getIsScreenRecordVideo() {
        return this._videoPath != "" && this._recorderEndTime - this._recorderTime > 8000;
    }

    getRecorderState() {
        return this._isRecorder;
    }
    getRecorderTime() {
        // return this._recorderEndTime-this._recorderTime;
        let now = new Date().getTime();
        return now - this._recorderTime;
    }

    shareRecorder(options) {
        let that = this;
        if (this._videoPath == "") {
            that.showToast("正在准备视频,请稍后...");
            return;
        }
        let query = "";
        globalThis.tt.shareAppMessage({
            channel: "video",
            title: that._shareTitle,
            desc: that._shareDesc,
            templateId: that._shareId, // 替换成通过审核的分享ID
            query: query,
            extra: {
                videoPath: that._videoPath, // 可替换成录屏得到的视频地址
                videoTopics: that._videoTopics,
                withVideoId: true
            },
            success(res) {
                console.log("分享视频成功");
                options.success && options.success(res.videoId);
                that._videoPath = "";
                that.sendEvent({ key: "shareVideoSuccess" });
            },
            fail(e) {
                console.log("分享视频失败", e);
                that.showToast("分享失败，请重试！");
                options.fail && options.fail(e);
            },
            complete() {

            }
        });
        that.sendEvent({ key: "shareVideo" });
    }

    //展示激励视频广告
    showRewardVideo(options: { success: Function, fail: Function }) {
        let that = this;
        that._videoOptions = options;
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) {
            that._videoOptions && that._videoOptions.success && that._videoOptions.success();
            that.sendEvent({ key: "playVideoSuccess" });
            return;
        }
        if (!that._videoAd) {
            //视频广告
            this._videoAd = globalThis.tt.createRewardedVideoAd({
                adUnitId: that._videoId
            });
            this._videoAd.onLoad(() => {
                console.log("广告加载完成");
            });
            this._videoAd.onError(res => {
                that._videoLoaded = false;
                that.sendEvent({ key: "videoError", value: { code: res.errCode } });
                setTimeout(function () {
                    that._videoAd.load().then(() => {
                        that._videoLoaded = true;
                    });
                }, 30000);
                that.showToast("暂无广告，你可以分享录屏获取奖励");
                console.log("视频加载失败", res.errCode);
            });

            this._videoAd.onClose(res => {
                that._videoLoaded = false;
                that.lastAdTime = new Date().getTime();
                if (res.isEnded) {
                    that._videoOptions && that._videoOptions.success && that._videoOptions.success();
                    that.sendEvent({ key: "playVideoSuccess" });
                } else {
                    that._videoOptions && that._videoOptions.fail && that._videoOptions.fail();
                    that.sendEvent({ key: "playVideoFail" });
                }
            });
            this._videoAd.load().then(() => {
                that._videoLoaded = true;
                that._videoAd.show().then(() => {
                    console.log("显示广告成功");
                }).catch(err => {
                    console.log("显示广告错误", err)
                    // 可以手动加载一次
                    that._videoAd.load().then(() => {
                        // 加载成功后需要再显示广告
                        return that._videoAd.show();
                    });
                });
            });
        } else {
            this._videoAd.show().then(() => {
                console.log("显示广告成功");
            }).catch(err => {
                console.log("显示广告错误", err)
                // 可以手动加载一次
                that._videoAd.load().then(() => {
                    // 加载成功后需要再显示广告
                    return that._videoAd.show();
                });
            });
        }
    }

    //设置系统剪贴板内容。可以和tt.getClipboardData配套使用
    setClipboardData(options: { data, success: Function, fail: Function }) {
        globalThis.tt.setClipboardData({
            data: options.data,
            success: (res) => {
                options.success && options.success(res);
                console.log("调用剪切板成功", options.data);
            },
            fail: (res) => {
                options.fail && options.fail(res);
                console.log("调用剪切板失败", options.data);
            }
        });
    }

    getVideoState() {
        return this._videoLoaded;
    }

    getLastAdTime() {
        return this.lastAdTime;
    }

    //显示插屏广告
    playScreen() {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        var res = globalThis.tt.getSystemInfoSync();
        if (res.platform == "ios") {
            return;
        }
        if (res.appName == "XiGua") {
            return;
        }
        let that = this;
        let now = new Date().getTime();
        if (now - this.lastAdTime > 60000) {
            if (that._interstitiaAd && that.screenShow) {
                try {
                    that._interstitiaAd.destroy();
                    that._interstitiaAd = null;
                } catch (error) {
                    console.log("销毁插屏广告失败", error);
                }
            }
            if (that._interstitiaAd && !that.screenShow) {
                that._interstitiaAd.load();
            } else {
                console.log("插屏不存在或已经播放，重新创建");
                that._interstitiaAd = globalThis.tt.createInterstitialAd({
                    adUnitId: that._screenId,
                });
                that._interstitiaAd.onLoad(() => {
                    console.log("插屏广告加载成功");
                    that._interstitiaAd.show().then(() => {
                        console.log("插屏广告展示成功");
                        that.screenShow = true;
                        that.lastAdTime = new Date().getTime();
                    });
                });
                that._interstitiaAd.onError((res) => {
                    console.log("插屏广告加载失败", res);
                    that.screenShow = false;
                });
            }
        }
    }

    sendEvent(options) {
        if (!options || !options.key) {
            return;
        }
        if (cc.sys.platform === cc.sys.BYTEDANCE_GAME) {
            console.log("上报事件:", options);
            // if (options.value) {
            //     globalThis.tt.reportAnalytics(options.key, options.value);
            // } else {
            //     globalThis.tt.reportAnalytics(options.key, {});
            // }
        }
    }

    //短震动：使手机发生较短时间的振动。Android 震动时间为 30ms，iOS 震动时间为 15ms
    vibrateShort() {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        if (this._shakeState) return;
        let now = new Date().getTime();
        if (now - this.lastshockTime > 100) {
            this.lastshockTime = now;
            globalThis.tt.vibrateShort({
                success(res) { },
                fail(res) {
                    console.log(`vibrateShort调用失败`);
                }
            });
        }
    }

    //长震动：使手机发生较长时间的振动（400 ms)
    vibrateLong() {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        if (this._shakeState) return;
        globalThis.tt.vibrateLong({
            success(res) { },
            fail(res) {
                console.log(`vibrateLong调用失败`);
            }
        })
    }

    getShakeState(): boolean {
        return this._shakeState;
    }

    setShakeState(bool: boolean) {
        this._shakeState = bool;
    }

    // 显示灰色背景的消息提示框，用以提供成功、警告和错误等反馈信息
    showToast(content: string, success?: Function, fail?: Function) {
        globalThis.tt.showToast({
            title: content,
            icon: "none",
            duration: 1500,
            success: (res) => {
                success && success();
            },
            fail: (res) => {
                fail && fail();
            },
        })
    }

    share(options: { title?: string, success?: Function, fail?: Function }) {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        this._shareOptions = options;
        globalThis.tt.shareAppMessage(options);
    }
    setLocalStorage(key: string, value: string | number | boolean) {
        cc.sys.localStorage.setItem(key, value);
    }

    getLocalStorage(key: string) {
        return cc.sys.localStorage.getItem(key);
    }

    sendHttpRequest(url, data, successBack: Function, failBack: Function) {
        globalThis.tt.request({
            url: url,
            data: data,
            success(res) {
                console.log(`request调用成功 `, res);
                if (res.data.ok) {
                    if (successBack) {
                        let result = res.data;
                        successBack(result);
                    }
                } else {
                    if (failBack) {
                        failBack(res.data.msg);
                    }
                }
            },
            fail(res) {
                console.log(`request调用失败`, res);
                if (failBack) {
                    failBack("网络繁忙,请稍后再试");
                }
            },
        });
    }


    contentSafe(options) {
        // let data = { text: options.content };
        // this.sendHttpRequest(Common.contentSafeTT, data, (res) => {
        //     if (res.valid) {
        //         options.callBack(true);
        //     } else {
        //         options.callBack(false);
        //     }
        // }, (res) => {
        //     options.callBack(false);
        // })
    }

    //分包
    public ttSubpackage(name: string, callback?: Function) {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        globalThis.tt.loadSubpackage({
            name: name, // name 可以填 name 或者 root
            success: function (res) {
                // 分包加载成功后通过 success 回调
                if (callback) callback(true, res);
            },
            fail: function (res) {
                // 分包加载失败通过 fail 回调
                if (callback) callback(false, res);
            }
        })
    }

    public checkSidebar(callback?: Function) {
        return new Promise((resolve, reject) => {
            if (cc.sys.platform === cc.sys.BYTEDANCE_GAME && !this.isSidebarShowed) {
                globalThis.tt.checkScene({
                    scene: "sidebar",
                    success: (res) => {
                        console.log("check scene success: ", res.isExist);
                        //成功回调逻辑
                        resolve(res.isExist);
                        callback && callback(res.isExist);
                    },
                    fail: (res) => {
                        console.log("check scene fail:", res);
                        //失败回调逻辑
                        resolve(false);
                        callback && callback(false);
                    }
                })
            } else {
                callback && callback(false);
            }
        })
    }

    //显示侧边栏
    public showSidebar(options: { success?: Function, fail?: Function }) {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        globalThis.tt.navigateToScene({
            scene: "sidebar",
            success: (res) => {
                console.log("navigate to scene success");
                // 跳转成功回调逻辑
                options.success && options.success();
            },
            fail: (res) => {
                console.log("navigate to scene fail: ", res);
                // 跳转失败回调逻辑
                options.fail && options.fail();
            },
        });
    }

    //展示抖音自带排行榜界面
    public showRank() {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        console.log("拉取排行榜");

        globalThis.tt.getImRankList({
            relationType: "default",
            dataType: 1,
            rankType: "day",
            rankTitle: "每日排行榜", //标题
            pageNum: 1,
            pageSize: 20,
            zoneId: "default"
        })
    }

    public sendRankData(options: { value: string, priority: number }) {
        if (cc.sys.platform !== cc.sys.BYTEDANCE_GAME) return;
        console.log("发送自己的数据");

        globalThis.tt.setImRankData({
            dataType: 1, //成绩为枚举类型，因为段位不是一个数字
            value: options.value, //"秩序白银", //该用户段位为白银
            priority: options.priority, //dataType为 1，需要权重，该游戏排序为 青铜（1）、白银（2）、黄金（3）、王者（4），因此此处传2
            extra: "extra",
            zoneId: "default",
            success(res) {
                console.log(`setImRankData success res: ${res}`);
            },
            fail(res) {
                console.log(`setImRankData fail res: ${res.errMsg}`);
            },
        });
    }
};
